﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.WebNemo.Business.Groups;
using blackhouse.WebNemo.Web;
using blackhouse.BlackApart.Web;
using blackhouse.mojoPortalExtend;
using blackhouse.BlackApart.Business.Reservations;
using blackhouse.BlackApart.Business.Apartments;
using blackhouse.BlackApart.Web.Modules;
using blackhouse.BlackApart.Business.Prices;
using System.Globalization;

namespace blackhouse.Aparts.Web.Modules {
    public partial class SelectedEvent : System.Web.UI.UserControl {

        private DateTime dt1, dt2;

        public void PopulateEvent(GroupRecord record) {
            this.ltlTitle.Text = record.GetString("tytul");

            string url = record.GetString("url");
            url = UrlUtils.LocalizeUrl(url.ReplaceEx("~/", "/"));

            string title = record.GetString("tytul");
            string photoDesc = record.GetString("opis_zdjecia");
            string photoAuth = record.GetString("autor_zdjecia");

            if (imgPhoto != null) {
                imgPhoto.ToolTip = photoDesc;
                imgPhoto.ImageUrl = record.GetImageUrl("zdjecie", new System.Drawing.Size(420, 1000));
            }

            if (ltlLead != null)
                ltlLead.Text = record.GetString("lid");

            if (ltlDate != null)
                ltlDate.Text = record.CreatedTime.ToString("g");

            if (ltlContent != null)
                ltlContent.Text = record.GetString("tresc");

            if (ltlPhotoAuthor != null)
                ltlPhotoAuthor.Text = photoAuth;

            if (ltlPhotoDescription != null)
                ltlPhotoDescription.Text = photoDesc;

            this.lnkPublish.Visible = blackhouse.WebNemo.Business.Factory.Instance().GetCurrentUser().HasSufficientPermissions(false) && !record.GetBoolean("publiczna");
            this.lnkPublish.CommandArgument = record.RecordId.ToString();

            bool datesSet = this.PopulateEventDates(record);
            if (datesSet && record.GetBoolean("czy_apartamenty")) {


                // LECIMY Z NOWYM FILTROWANIEM
                if (dt1.Date == dt2.Date)
                    dt2 = dt2.AddDays(1);
                FreeApartments search = new FreeApartments(dt1, dt2, 1);
                if (search.Count() >= 3) {
                    this.pnlApartments.Visible = true;
                    this.rptApartments.DataSource = search.OrderByDescending(vv => vv.GetGroups().First().Stars).Take(3);
                    this.rptApartments.DataBind();
                    this.pnlApartments.Visible = true;

                    ltlReservationDate.Text = this.GetEventDates(dt1, dt2);
                }
            }

            PageProvider pp = new PageProvider();
            pp.SetCanonicalUrl(url);
            pp.SetPageDescription(ltlLead.Text);
            pp.SetPageTitle(title);
        }

        protected void lnkPublish_Click(object sender, EventArgs e) {
            int recordId = Int32.Parse((sender as LinkButton).CommandArgument);
            IGroup group = blackhouse.WebNemo.Business.Factory.Instance().GetGroup("wydarzenia_" + CultureInfo.CurrentCulture.Name.Split('-').First());
            IGroupRecord iRecord = group.GetGroupRecord(recordId, CultureInfo.CurrentCulture);
            GroupRecord gr = new GroupRecord(group, iRecord, CultureInfo.CurrentCulture);
            gr.SetValue("publiczna", true);
            gr.Save();
            Response.Redirect(Request.RawUrl);
        }

        protected void rptApartments_ItemDataBound(object sender, RepeaterItemEventArgs e) {
            switch (e.Item.ItemType) {
                case ListItemType.Item:
                case ListItemType.AlternatingItem:
                    Variant v = e.Item.DataItem as Variant;
                    IApartmentGroup group = null;
                    if (v != null)
                        group = v.GetGroups().First();
                    if (group != null) {
                        HyperLink lnkName = e.Item.FindControl("lnkName") as HyperLink;
                        HyperLink lnkMaxPeople = e.Item.FindControl("lnkMaxPeople") as HyperLink;
                        Panel pnlItem = e.Item.FindControl("pnlItem") as Panel;
                        Panel pnlMaxPeople = e.Item.FindControl("pnlMaxPeople") as Panel;
                        CurrencyLiteral lblPricePersonNight = e.Item.FindControl("lblPricePersonNight") as CurrencyLiteral;
                        if (lnkName != null) {
                            lnkName.NavigateUrl = UrlUtils.GetApartmentTypeUrl(group, DisplayApartmentTypeView.Default, 1, SearchState.GetState(dt1, dt2, 1));
                            lnkName.ToolTip = group.Name;
                            lnkName.Text = group.ShortName + "<span class=\"eva-ap-titi\"> - sprawdź</span>";
                        }

                        if (pnlItem != null) {
                            pnlItem.BackImageUrl = UrlUtils.GetDbImageUrl("Apartment-photo", group.MainPhoto.PhotoName, new System.Drawing.Size(310, 310));
                        }

                        if (lblPricePersonNight != null) {
                            lblPricePersonNight.Value = v.Price.GetPricePerNight();
                        }

                        if (pnlMaxPeople != null && lnkMaxPeople != null) {
                            pnlMaxPeople.Width = Unit.Pixel(group.NumberOfPeople * 11);

                            string lnkPeople_tooltip = GetGlobalResourceObject("Aparts", "apartmentsPeopleCount").ToString();
                            if (!string.IsNullOrEmpty(lnkPeople_tooltip) && lnkPeople_tooltip.Contains("{0}"))
                                lnkMaxPeople.ToolTip = string.Format(lnkPeople_tooltip, group.NumberOfPeople);
                        }
                    }
                    break;
            }

        }

        private bool PopulateEventDates(GroupRecord record) {
            if (record.IsNull("data_od") || record.IsNull("data_do")) {
                pnlEventDates.Visible = false;
                return false;
            }

            dt1 = record.GetDateTime("data_od").Date;
            dt2 = record.GetDateTime("data_do").Date;
            DateTime dtn = DateTime.Now.Date;

            if (dt1 < DateTime.Now.Date && dt2 > dtn)
                dt1 = dtn;

            if (dt1 < dtn) return false;
            if (dt1 > dt2) return false;

            this.ltlEventDate.Text = this.GetEventDates(dt1, dt2);
            return dt1 >= DateTime.Now.Date;
        }

        private string GetEventDates(DateTime dt1, DateTime dt2) {

            string s = "";

            if (dt1.Date.Equals(dt2.Date))
                s = dt1.ToString("d MMMM yyyy");
            else {
                s = dt1.ToString(this.GetFormatStartDate(dt1, dt2));
                s += (" - " + dt2.ToString("d MMMM yyyy"));
            }
            return s;
        }

        private string GetFormatStartDate(DateTime dt1, DateTime dt2) {
            if (dt1.Year != dt2.Year)
                return "d MMMM yyyy";
            else {
                string format = "d ";
                if (dt1.Month != dt2.Month)
                    format += "MMMM";
                return format;
            }

        }

    }
}